package com.hulu.yec.stu.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.hulu.yec.stu.dao.StuUserDao;
import com.hulu.yec.stu.entity.StuUserEntity;
import com.hulu.yec.sys.user.entity.SysUserEntity;

@WebServlet("/stu/StuUserServlet")
public class StuUserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private StuUserDao stuUserDao = new StuUserDao();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 解决乱码
		request.setCharacterEncoding("UTF-8");
		String command = request.getParameter("command");
		if ("list".equals(command)) {
			try {
				try {
					list(request, response);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			throw new RuntimeException("错误！");
		}

	}

	/**
	 * 查询
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 * @throws SQLException
	 * @throws ParseException
	 */

	private void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException, ParseException {
		// 1,接受参数、条件查询参数
		SysUserEntity sysUserEntity = (SysUserEntity) request.getSession()
				.getAttribute("user");
		if (sysUserEntity == null) {
			request.getRequestDispatcher("/WEB-INF/view/common/login.jsp")
			.forward(request, response);
		} else {
			int id = sysUserEntity.getId();

			// 2,调用业务逻辑
			List<StuUserEntity> stuUserList = stuUserDao.list(id + "");
			request.setAttribute("stuUserList", stuUserList);
			// 3,转向
			try {
				request.getRequestDispatcher("/WEB-INF/view/stu/student.jsp")
						.forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
